package com.allen.retrofit2_rxjava2.app;

import android.app.Activity;
import android.app.ActivityManager;
import android.app.Application;
import android.content.Context;
import android.os.Bundle;
import android.text.TextUtils;

import com.allen.retrofit2_rxjava2.crashhandler.UICrashHandler;
import com.allen.retrofit2_rxjava2.network.interceptor.CookieReadInterceptor;
import com.allen.retrofit2_rxjava2.network.interceptor.CookiesSaveInterceptor;
import com.allen.retrofit2_rxjava2.network.utils.InterceptorUtil;
import com.allen.retrofit2_rxjava2.utils.MainUtil;
import com.ieyelf.service.util.Logger;
import com.ieyelf.service.util.MetaUtil;

import java.util.List;
import java.util.concurrent.TimeUnit;

import okhttp3.OkHttpClient;

/**
 * @author:
 * @date: 2018/7/25
 * @description: application
 */

public class MyApp extends Application {
    public static MyApp myApp;
    private static Context context;
    private static Activity curActivity;
    public static final int TIMEOUT = 60;
    private static OkHttpClient mOkHttpClient;
    public final static String URL_META_DATA_DEBUG_LOG = "DEBUG_LOG";
    public final static String URL_DEBUG_LOGSET = "DEBUG_LOGSET";
    public static String debug_log = "open_debug_log";
    public static boolean debug = true;

    @Override
    public void onCreate() {
        super.onCreate();

        //判断当前进程是否是本进程 进程会调用多次 创建多个对象
        String processName = getProcessName(this, android.os.Process.myPid());
        if (processName != null) {
            //判断当前的进程是我们自己app
            boolean defaultProcess = processName.equals("com.allen.retrofit2_rxjava2");//自己的包名
            if (defaultProcess) {
                //当前应用的初始化
                init();
            }
        }
    }


    public String getProcessName(Context cxt, int pid) {
        ActivityManager am = (ActivityManager) cxt.getSystemService(Context.ACTIVITY_SERVICE);
        List<ActivityManager.RunningAppProcessInfo> runningApps = am.getRunningAppProcesses();
        if (runningApps == null) {
            return null;
        }
        for (ActivityManager.RunningAppProcessInfo procInfo : runningApps) {
            if (procInfo.pid == pid) {
                return procInfo.processName;
            }
        }
        return null;
    }

    /**
     * 初始化进程
     *
     * @brief
     * @details
     */
    private void init() {
        myApp = this;
        context = getApplicationContext();
        initLogger();
        initCrashHandler();

        registerActivityLifecycleCallbacks(lifecycleCallbacks);

    }

    /**
     * 初始化日志
     */
    private void initLogger() {
        try {
            String debug_log_temp = MetaUtil.getAppMetaData(context, URL_META_DATA_DEBUG_LOG);
            debug_log = TextUtils.isEmpty(debug_log_temp) || TextUtils.equals(debug_log_temp, URL_DEBUG_LOGSET) ? debug_log : debug_log_temp;
            debug = TextUtils.equals(debug_log, "open_debug_log");
            MainUtil.setDebug(debug);//日志开关
        } catch (Exception e) {
            MainUtil.setDebug(false);//日志关
        }

    }

    /**
     * 初始化崩溃日志本地采集
     */
    private void initCrashHandler() {
        UICrashHandler uiCrashHandler = UICrashHandler.getInstance();
        uiCrashHandler.init(context);
    }

    /**
     * 全局httpclient
     *
     * @return
     */
    public static OkHttpClient initOKHttp() {
        if (mOkHttpClient == null) {
            mOkHttpClient = new OkHttpClient.Builder()
                    .connectTimeout(TIMEOUT, TimeUnit.SECONDS)//设置连接超时时间
                    .readTimeout(TIMEOUT, TimeUnit.SECONDS)//设置读取超时时间
                    .writeTimeout(TIMEOUT, TimeUnit.SECONDS)//设置写入超时时间
                    .addInterceptor(InterceptorUtil.LogInterceptor())//添加日志拦截器
                    //cookie
                    .addInterceptor(new CookieReadInterceptor())
                    .addInterceptor(new CookiesSaveInterceptor())
                    .build();
        }
        return mOkHttpClient;
    }

    public static Context getContext() {
        return context;
    }

    public static Activity getCurActivity() {
        return curActivity;
    }

    public static void setCurActivity(Activity curActivity) {
        MyApp.curActivity = curActivity;
    }


    private ActivityLifecycleCallbacks lifecycleCallbacks = new ActivityLifecycleCallbacks() {

        @Override
        public void onActivityStopped(Activity activity) {

        }

        @Override
        public void onActivityStarted(Activity activity) {

        }

        @Override
        public void onActivitySaveInstanceState(Activity activity,
                                                Bundle outState) {

        }

        @Override
        public void onActivityResumed(Activity activity) {
            curActivity = activity;
        }

        @Override
        public void onActivityPaused(Activity activity) {

        }

        @Override
        public void onActivityDestroyed(Activity activity) {

        }

        @Override
        public void onActivityCreated(Activity activity,
                                      Bundle savedInstanceState) {
            curActivity = activity;
        }
    };

}
